# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import logging
import time


class RestRateLimiter(object):
  def __init__(self, delay, logger=None, verbose=True):
    assert 0 < delay < 500, delay
    self._delay = delay
    self._last_error_code = None
    self._last_error_timestamp = None
    self._logger = logger or logging.getLogger(__name__)
    self._verbose = verbose

  def is_available(self, current=None):
    if current is None:
      current = time.time()

    if self._last_error_timestamp is not None and \
       self._last_error_timestamp + self._delay >= current:
      return False

    return True

  def check(self, current=None):
    return self.is_available(current=current)

  def reset_error(self):
    self._last_error_code = None
    self._last_error_timestamp = None

  def set_error(self, status_code, current=None):
    if current is None:
      current = time.time()

    self._last_error_code = status_code
    self._last_error_timestamp = current
